﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Reflection;
using Jy.Extensions;

namespace Jy.Abp.Enums;

public static class EnumHelper
{
    private static List<Type> _enumTypes = new List<Type>();
    private static List<Assembly> _regedAssemblies = new List<Assembly>();

    /// <summary>
    /// 注册程序集中的所有枚举类型到管理中
    /// </summary>
    public static void RegisterAssemblies(params Assembly[] assemblies)
    {
        foreach (var assembly in assemblies)
        {
            if (_regedAssemblies.Any(t => t.FullName == assembly.FullName))
                return;
            _regedAssemblies.Add(assembly);
            var types = assembly.GetTypes()
              .Where(t => t.IsEnum && (t.IsPublic || t.IsNestedPublic));
            _enumTypes.AddRange(types);
        }
    }
    /// <summary>
    /// 获取当前系统所有的枚举类型
    /// </summary>
    public static IEnumerable<Type> GetAllTypes(Func<Type, bool> condition = null)
    {
        return _enumTypes.WhereIf(condition != null, condition);
    }
    /// <summary>
    /// 获取指定类型的枚举数据
    /// </summary>
    public static List<EnumItem> GetItems(Type enumType)
    {
        var ops = Enum.GetValues(enumType);
        var items = new List<EnumItem>();
        foreach (var o in ops)
        {
            var item = new EnumItem();
            //var key = o.GetLanguateKey();
            item.Value = Convert.ToInt32(o);
            item.Name = o.ToString();
            item.Desc = o.GetDesc(false);
            items.Add(item);
        }
        return items;
    }
    /// <summary>
    /// 获取指定类型的枚举数据
    /// </summary>
    public static List<EnumItem> GetItems<TEnum>()
    {
        return GetItems(typeof(TEnum));
    }
    /// <summary>
    /// 获取所有指定名称的枚举列表
    /// </summary>
    public static IDictionary<string, List<EnumItem>> GetAllItems(Func<Type, bool> predicate = null)
    {
        var types = _enumTypes.WhereIf(predicate != null, predicate);

        var dic = new Dictionary<string, List<EnumItem>>();
        foreach (var type in types)
        {
            dic.Add(type.Name, GetItems(type));
        }

        return dic;
    }
    /// <summary>
    /// 获取所有需要返回给客户端的枚举项
    /// </summary>
    public static IDictionary<string, List<EnumItem>> GetShowOnApiItems()
    {
        return GetAllItems(t => t.CustomAttributes.Any(x => x.AttributeType == typeof(ShowOnApiAttribute)));
    }
}
